﻿using AutoMapper;
using MediatR;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;
using Yitter.IdGenerator;

namespace RearLivestock.Beginning.Api.Application.Command.PigBreedings
{
    /// <summary>
    /// 种母配种信息添加Handler
    /// </summary>
    public class AddPigsBreedingHandler : IRequestHandler<AddPigsBreedingCommand, Result>
    {
        private readonly IMapper mapper;
        /// <summary>
        /// 种母配种
        /// </summary>
        private readonly IBaseRepository<PigsBreeding> pigsBreedingrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<AddPigsBreedingHandler> _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="pigsBreedingrepository"></param>
        /// <param name="logger"></param>
        public AddPigsBreedingHandler(IMapper mapper, IBaseRepository<PigsBreeding> pigsBreedingrepository, ILogger<AddPigsBreedingHandler> logger)
        {
            this.mapper = mapper;
            this.pigsBreedingrepository = pigsBreedingrepository;
            _logger = logger;
        }
        /// <summary>
        /// 种母配种
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(AddPigsBreedingCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                var num = 1001;
                foreach (var item in request.pigsBreedings)
                {
                    //流水号
                    item.SerialNo = YitIdHelper.NextId().ToString();
                    //单据号
                    item.DocumentNo = DateTime.Now.ToString("yyyyMMddHHmmss") + num;
                    num++;
                }
                var res = pigsBreedingrepository.AddRange(request.pigsBreedings);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加种母配种成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "添加种母配种异常" + ex.Message;
                _logger.LogError("添加种母配种异常" + ex.Message);
            }
            return result;
        }
    }
}
